package cn.my.framework.config.shiro;

import cn.my.framework.util.CommonUtils;
import cn.my.framework.util.ConstantData;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by zhangl_lc on 2017/7/31.
 */
public class MyCheckCodeFilter extends AccessControlFilter {
    Logger logger = LoggerFactory.getLogger(MyCheckCodeFilter.class);

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        if(ConstantData.codeCheckEnable && StringUtils.equalsIgnoreCase("post",req.getMethod())){
            HttpSession session = req.getSession();
            String checkcode = req.getParameter("checkcode");
            String cachedCode = CommonUtils.getCachedCheckCode(session.getId());
            logger.debug(">>>>> checkCode={},cachedCode={},sessionId={}",checkcode,cachedCode,session.getId());
            if(StringUtils.isNoneBlank(checkcode) &&
                    StringUtils.equalsIgnoreCase(checkcode, cachedCode)){
                return true;
            }
            req.setAttribute("message", "验证码错误！");
            req.setAttribute("username", request.getParameter("username"));
            return false;
        }
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        logger.debug(">>>>> AccessDenied >>> {}",request.getAttribute("message"));
        //WebUtils.issueRedirect(request,response,"/login");
        request.getRequestDispatcher("/login").forward(request,response);
        return false;
    }
}
